package com.springboot.myweb.controller;

import com.springboot.myweb.service.UserService;
import com.springboot.myweb.utils.JsonResult;
import com.springboot.myweb.utils.Log4jUtil;
import com.springboot.myweb.utils.MD5Util;
import com.springboot.myweb.pojo.User;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("User")
public class UserController {

    @Autowired
    private UserService userService;

    //log4j
    private Logger log  = Log4jUtil.getLog(UserController.class);

    @PostMapping("check_login")
    @ResponseBody
    @ApiOperation("用户登录")
    public JsonResult check_login(User user, Model model, HttpSession session){
        JsonResult jsonResult = new JsonResult();
        String msg="";
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //取token
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), MD5Util.GetMD5Code(user.getPassword(),true));

        try{
            //令牌登录
            subject.login(usernamePasswordToken);
            msg="登录成功";
            session.setAttribute("user",user.getUsername());
            Session session1 =  subject.getSession();
            jsonResult.setStatus(JsonResult.STATUS_SUCCESS);
            jsonResult.setMessage(msg);
            return jsonResult;
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名错误");
            jsonResult.setStatus(JsonResult.STATUS_ERROR);
            return jsonResult;
        }catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg","密码错误");
            jsonResult.setStatus(JsonResult.STATUS_ERROR);
            return jsonResult;
        }

    }



    @GetMapping("/sync")
    @ResponseBody
    public String sync(){
        userService.sync();//测试一个异步
        return "sync";
    }


}
